<template>
  <div class="production-plan">
    <el-button type="primary" @click="saveAll">保存主表单和明细</el-button>
    <h3 class="title">货物信息</h3>
    <!-- 基本信息 -->
    <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="产品名称">
            <el-input v-model="formData.productName" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产品编号">
            <el-input v-model="formData.productId" placeholder="请输入" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="所属类别" prop="category">
            <el-select v-model="formData.category" placeholder="请选择">
              <el-option label="汽车行业" value="汽车行业" />
              <el-option label="医疗行业" value="医疗行业" />
              <el-option label="工程行业" value="工程行业" />
              <el-option label="电子行业" value="电子行业" />
              <el-option label="食品行业" value="食品行业" />
              <el-option label="纺织行业" value="纺织行业" />
              <el-option label="家具行业" value="家具行业" />
              <el-option label="化工行业" value="化工行业" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单位">
            <el-select v-model="formData.unit" placeholder="请选择">
              <el-option label="个" value="个" />
              <el-option label="双" value="双" />
              <el-option label="套" value="套" />
              <el-option label="件" value="件" />
              <el-option label="箱" value="箱" />
              <el-option label="盒" value="盒" />
              <el-option label="克" value="克" />
              <el-option label="千克" value="千克" />
              <el-option label="吨" value="吨" />
              <el-option label="米" value="米" />
              <el-option label="瓶" value="瓶" />
              <el-option label="桶" value="桶" />
              <el-option label="张" value="张" />
              <el-option label="辆" value="辆" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="规格型号">
            <el-input v-model="formData.specificationModel" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="单价">
            <el-input-number v-model="formData.unitPrice" placeholder="请输入" :min="0" :step="1" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产品说明">
            <el-input v-model="formData.productDescription" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否为实体" prop="isEntity">
            <el-radio-group v-model="formData.isEntity">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否含税" prop="isTaxIncluded">
            <el-radio-group v-model="formData.isTaxIncluded">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产品属性" prop="isSelfMade">
            <el-select v-model="formData.isSelfMade" placeholder="请选择">
              <el-option label="自制" value="1"></el-option>
              <el-option label="委外" value="2"></el-option>
              <el-option label="外购" value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
                <el-form-item label="主供应商" >
                    <el-input 
                    placeholder="请输入" 
                    v-model="formData.mainSupplier" 
                    required
                  >
                    <template #suffix>
                      <el-button size="mini" @click="openAssociatedItemDialog1">
                        <i class="el-icon-search"></i>
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="安全库存">
            <el-input-number v-model="formData.safetyStock" placeholder="请输入" :min="0" :step="1" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="库存下限">
            <el-input-number v-model="formData.inventoryLowerLimit" placeholder="请输入" :min="0" :step="1" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="库存上限">
            <el-input-number v-model="formData.inventoryUpperLimit" placeholder="请输入" :min="0" :step="1" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="耗损率(%)">
            <el-input-number v-model="formData.lossRate" placeholder="请输入" :min="0" :step="1" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产品有效期（天）">
            <el-input-number v-model="formData.productValidityDays" placeholder="请输入" :min="0" :step="1" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="养护周期">
            <el-input v-model="formData.maintenanceCycle" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="条形码信息">
            <el-input v-model="formData.barcodeImage" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div id="app">
      <el-card>
        <template #header>
          <div class="flex justify-between items-center">
            <span>MinIO 文件上传</span>
          </div>
        </template>
        <el-form ref="formRef1" :model="formData1" label-width="100px">
          <el-form-item label="选择文件">
            <el-upload ref="uploadRef" action="https://localhost:7269/api/FileUpload/UploadFile" :headers="headers"
              :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :http-request="customRequest">
              <el-button type="primary">选择文件</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">上传文件</el-button>
          </el-form-item>
        </el-form>
        <el-alert v-if="message" :message="message" :type="messageType" :closable="false" style="margin-top: 20px" />
      </el-card>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="key" label="文件名称" width="200" />
        <el-table-column prop="lastModified" label="创建时间" width="200">
          <template #default="scope">
            {{ new Date(scope.row.lastModified).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="size" label="文件大小" min-width="200" />
        <el-table-column fixed="right" label="操作" min-width="200">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="openDeleteDialog(scope.row.key)">
              删除文件
            </el-button>
            <el-button link type="primary" size="small" @click="download(scope.row.key)">下载文件</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-model="isDeleteDialogVisible" title="删除确认" @close="closeDeleteDialog">
        <p>确定要删除该文件吗？</p>
        <template #footer>
          <el-button @click="closeDeleteDialog">取消</el-button>
          <el-button type="primary" @click="confirmDelete">确定</el-button>
        </template>
      </el-dialog>
      <el-dialog v-model="isDownloadDialogVisible" title="文件下载">
        <template #content>
          <el-progress :percentage="downloadProgress" :status="downloadStatus"></el-progress>
        </template>
        <template #footer>
          <el-button @click="closeDownloadDialog">关闭</el-button>
        </template>
      </el-dialog>
    </div>
    <!-- 供应商选择对话框 -->
    <el-dialog
        v-model="associatedItemDialogVisible1"
        width="500px"
        title="供应商选择"
        append-to-body
      >
        <el-table
          :data="associatedItems1"
          highlight-current-row
          border
          size="small"
          @current-change="handleAssociatedItemChange1"
        >
         <el-table-column type="index" label="序号" />
          <el-table-column property="vendorName" label="供应商名称" />
          <el-table-column property="supplierNumber" label="供应商编号" />
          <el-table-column property="industry" label="供应商类别" />
          <el-table-column property="contact" label="联系人" />
          <el-table-column property="sex" label="性别" />
          <el-table-column property="origin" label="籍贯" />
          <el-table-column property="phone" label="手机号码" />
          <el-table-column property="email" label="邮箱" />
          <el-table-column property="addr" label="地址" />
          <el-table-column property="companyProfile" label="公司简介" />
          <el-table-column property="bank" label="开户银行" />
          <el-table-column property="accountName" label="账户名称" />
          <el-table-column property="bankCardNumber" label="银行卡号" />
        </el-table>
        <template #footer>
          <el-button @click="pickAssociatedItem1">确定</el-button>
        </template>
      </el-dialog>
  
    
  </div>
</template>

  

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { Materialread, Materialwrite  } from '@/axios/axiosHelper';
import axios from 'axios';

const formRef = ref(null);
const currentUser = ref("admin");
const router = useRouter();
const route = useRoute();

// 主表单数据，使用驼峰命名规范，使变量命名更统一
const formData = reactive({
  "goodsModelId": route.query.goodsModelId,
  "productName": "",
  "productId": "",
  "category": "",
  "unit": "",
  "specificationModel": "",
  "unitPrice": 0,
  "productDescription": "",
  "isEntity": true,
  "isTaxIncluded": true,
  "isSelfMade": 0,
  "mainSupplier": "",
  "safetyStock": 0,
  "inventoryLowerLimit": 0,
  "inventoryUpperLimit": 0,
  "lossRate": 0,
  "productValidityDays": 0,
  "maintenanceCycle": "",
  "barcodeImage": "",
  "isDel": true
});


// 其他数值属性类似转换
import { nextTick } from 'vue';
const getProductionById = (goodsModelId) => {
  const GoodsModelId = route.query.goodsModelId;
  if (!GoodsModelId) {
    console.error('未获取到有效的goodsModelId');
    return;
  }
  axios.get('https://localhost:7090/api/Goods/FTGoods', {
    params: {
      GoodsModelId: goodsModelId
    }
  })
 .then(res => {
    const dataItem = res.data.data[0]; // 假设返回的数据是一个数组，且每个元素都有id和name属性
    formData.productName = dataItem.productName;
      formData.productId = dataItem.productId;
      formData.category = dataItem.category;
      formData.unit =dataItem.unit;
      formData.specificationModel = dataItem.specificationModel;
      formData.unitPrice = dataItem.unitPrice;
      formData.productDescription = dataItem.productDescription;
      formData.isEntity = dataItem.isEntity;
      formData.isTaxIncluded = dataItem.isTaxIncluded;
      formData.isSelfMade = dataItem.isSelfMade;
      formData.mainSupplier = dataItem.mainSupplier;
      formData.safetyStock = dataItem.safetyStock;
      formData.inventoryLowerLimit = dataItem.inventoryLowerLimit;
      formData.inventoryUpperLimit = dataItem.inventoryUpperLimit;
      formData.lossRate = dataItem.lossRate;
      formData.productValidityDays = dataItem.productValidityDays;
      formData.maintenanceCycle =dataItem.maintenanceCycle;
      formData.barcodeImage = dataItem.barcodeImage;
      formData.goodsModelId =dataItem.goodsModelId;

    nextTick(() => {
      // 这里可以确保数据赋值后更新视图
      console.log('进入nextTick，尝试更新视图');
    });
  });
};


const saveAll = async () => {
  try {
    const response = await axios.put('https://localhost:7279/api/Goods/UpdateGoods', formData);
    if (response.data) { // 增加对response.data的判断
      if (response.data.code === 400) { 
        ElMessage.success('主表单修改成功');
        router.push('/ShowGoods');
      } else {
        ElMessage.error(`主表单修改失败：${response.data.message}`);
      }
    } else {
      ElMessage.error('后端返回数据异常');
    }
  } catch (error) {
    console.error('保存错误:', error);
    ElMessage.error('保存失败，请检查网络或联系管理员');
  }
};

onMounted(() => {
 
        getProductionById(route.query.goodsModelId);
   
});
</script>

<style scoped>
.production-plan {
    padding: 20px;
}

.title {
    text-align: center;
    margin-bottom: 20px;
}

.sub-title {
    margin: 20px 0 10px;
    font-size: 16px;
    font-weight: 500;
}

.detail-section,
.attachment-section {
    margin-top: 20px;
}

.el-table {
    margin-top: 10px;
}
</style>